package com.example.project.dao;


import com.example.project.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;


@Mapper
public interface UserDAO extends JpaRepository<User,String>, JpaSpecificationExecutor<User> {

    // 1. 根据用户名查询（只返回指定字段）
    @Query(value = "select new User(u.id, u.userName, u.avatar, u.email, u.state, u.createTime, u.updateTime) from User as u where u.userName = :userName")
    User findOneByUserName(@Param("userName") String userName);

    // 2. 根据邮箱查询（只返回指定字段）
    @Query(value = "select new User(u.id, u.userName, u.avatar, u.email, u.state, u.createTime, u.updateTime) from User as u where u.email = :email")
    User findOneByEmail(@Param("email") String email);

    // 3. 根据ID查询（只返回指定字段）
    @Query(value = "select new User(u.id, u.userName, u.avatar, u.email, u.state, u.createTime, u.updateTime) from User as u where u.id = :userId")
    User findOneById(@Param("userId") Long userId);

    /**
     * 通过修改用户的状态来删除用户
     *
     * @param userId
     * @return
     */
    @Modifying
    @Query(nativeQuery = true, value = "UPDATE `tb_user` SET `state` = '0' WHERE `id` = ?")
    int deleteUserByState(Long userId);


    @Modifying
    @Query(nativeQuery = true, value = "UPDATE `tb_user` SET `password` = ? ,`salt` = ? WHERE `email` = ? ")
    int updatePasswordByEmail(String encodedPassword,String salt, String email);

    @Modifying
    @Query(nativeQuery = true, value = "UPDATE `tb_user` SET `email` = ? WHERE `id` = ? ")
    int updateEmailById(String email,Long userId);

    @Query(value = "select new User(u.id,u.userName,u.avatar,u.email,u.state,u.createTime,u.updateTime) from User as u")
    Page<User> listAllUser(Pageable pageable);


}
